from datetime import datetime
from socket import socket

from django.core.paginator import Paginator
from django.db.models import Count, Sum
from django.db.models.functions import TruncMonth
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from EmployeeSystemApp import models
from EmployeeSystemApp.utils.DataBI import computer
from EmployeeSystemApp.utils.Page import pageRange


# Create your views here.


# 部门列表
def depart_list(request):
    queryset = models.Department.objects.all()
    return render(request, 'depart_list.html', {"queryset": queryset, "username": request.session['username']})


# 部门添加
def depart_add(request):
    if request.method == 'GET':
        return render(request, 'depart_add.html', {"username": request.session['username']})
    title = request.POST.get('title')
    models.Department.objects.create(title=title)
    return redirect('/depart/list/')


# 部门删除
def depart_delete(request):
    ID = request.GET.get('id')
    models.Department.objects.filter(id=ID).delete()
    return redirect('/depart/list/')


# 部门更新
def depart_update(request, ID):
    if request.method == 'GET':
        departInfo = models.Department.objects.filter(id=ID).first()
        return render(request, 'depart_update.html',
                      {"departInfo": departInfo, "username": request.session['username']})
    title = request.POST.get('title')
    models.Department.objects.filter(id=ID).update(title=title)
    return redirect('/depart/list/')


# 员工列表
def user_list(request):
    info = request.GET.get('info')
    if info:
        queryset = models.UserInfo.objects.select(info)
        page = int(request.GET.get('page', 1))
        page_range, start, end, Pre, Next = pageRange(page, queryset)
        queryset = models.UserInfo.objects.select(info)[start: end]
        return render(request, 'user_list.html',
                      {"queryset": queryset, "page_range": page_range, "info": info, "search": True, "page": page,
                       "Pre": Pre, "Next": Next, "username": request.session['username']})
    else:
        queryset = models.UserInfo.objects.all()
        page = int(request.GET.get('page', 1))
        page_range, start, end, Pre, Next = pageRange(page, queryset)
        queryset = models.UserInfo.objects.all()[start: end]
        return render(request, 'user_list.html',
                      {"queryset": queryset, "page_range": page_range, "search": False, "page": page, "Pre": Pre,
                       "Next": Next, "username": request.session['username']})


# 员工添加
def user_add(request):
    if request.method == "GET":
        departInfo = models.Department.objects.all()
        return render(request, 'user_add.html', {"departInfo": departInfo, "username": request.session['username']})
    name, password, age, gender, salary, times, depart = request.POST.get('name'), request.POST.get(
        'password'), request.POST.get('age'), request.POST.get('gender'), request.POST.get('salary'), request.POST.get(
        'time'), request.POST.get('depart')
    models.UserInfo.objects.create(name=name, password=password, age=age, gender=gender, salary=salary,
                                   create_time=times, depart_id=depart)
    return redirect('/user/list/')


# 员工更新
def user_update(request, ID):
    if request.method == 'GET':
        userInfo = models.UserInfo.objects.filter(id=ID).first()
        departInfo = models.Department.objects.all()
        return render(request, 'user_update.html',
                      {"userInfo": userInfo, "departInfo": departInfo, "username": request.session['username']})
    name, password, age, gender, salary, times, depart = request.POST.get('name'), request.POST.get(
        'password'), request.POST.get('age'), request.POST.get('gender'), request.POST.get('salary'), request.POST.get(
        'time'), request.POST.get('depart')
    if times == '':
        models.UserInfo.objects.filter(id=ID).update(name=name, password=password, age=age, gender=gender,
                                                     salary=salary, depart_id=depart)
        return redirect('/user/list/')
    models.UserInfo.objects.filter(id=ID).update(name=name, password=password, age=age, gender=gender, salary=salary,
                                                 create_time=times, depart_id=depart)
    return redirect('/user/list/')


# 员工删除
def user_delete(request, ID):
    models.UserInfo.objects.filter(id=ID).delete()
    return redirect('/user/list/')


# 业务信息
def business_list(request):
    info = request.GET.get('info')
    if info:
        queryset = models.BusinessInfo.objects.search(info)
        page = int(request.GET.get('page', 1))
        page_range, start, end, Pre, Next = pageRange(page, queryset)
        queryset = models.BusinessInfo.objects.search(info)[start: end]
        return render(request, 'business_list.html',
                      {"queryset": queryset, "page_range": page_range, "info": info, "search": True, "page": page,
                       "Pre": Pre, "Next": Next, "username": request.session['username']})
    else:
        queryset = models.BusinessInfo.objects.all()
        page = int(request.GET.get('page', 1))
        page_range, start, end, Pre, Next = pageRange(page, queryset)
        queryset = models.BusinessInfo.objects.all()[start: end]
        return render(request, 'business_list.html',
                      {"queryset": queryset, "page_range": page_range, "search": False, "page": page, "Pre": Pre,
                       "Next": Next, "username": request.session['username']})


# 业务添加
def business_add(request):
    if request.method == 'GET':
        return render(request, 'business_add.html', {"username": request.session['username']})
    name, time, price, customer, phone, level, status = request.POST.get('name'), request.POST.get(
        'time'), request.POST.get('price'), request.POST.get('customer'), request.POST.get('phone'), request.POST.get(
        'level'), request.POST.get('status')
    models.BusinessInfo.objects.create(name=name, create_time=time, price=price, customer=customer, phone=phone,
                                       level=level, status=status)
    return redirect('/business/list/')


# 业务更新
def business_update(request, ID):
    if request.method == 'GET':
        BusinessInfo = models.BusinessInfo.objects.filter(id=ID).first()
        return render(request, 'business_update.html',
                      {"BusinessInfo": BusinessInfo, "username": request.session['username']})
    name, time, price, customer, phone, level, status = request.POST.get('name'), request.POST.get(
        'time'), request.POST.get('price'), request.POST.get('customer'), request.POST.get('phone'), request.POST.get(
        'level'), request.POST.get('status')
    models.BusinessInfo.objects.filter(id=ID).update(name=name, create_time=time, price=price, customer=customer,
                                                     phone=phone, level=level, status=status)
    return redirect('/business/list/')


# 业务删除
def business_delete(request, ID):
    models.BusinessInfo.objects.filter(id=ID).delete()
    return redirect('/business/list/')


# 登录
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    name, password = request.POST.get('username'), request.POST.get('password')
    exist = models.AdminInfo.objects.filter(username=name, password=password).first()
    if exist:
        request.session['username'] = name
        models.AdminInfo.objects.filter(username=name).update(login_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                                              login_IP=str(request.META['REMOTE_ADDR']))
        return redirect('/user/list/')
    else:
        return render(request, 'login.html', {'error': '用户名或密码错误'})


# 注册
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    name, password = request.POST.get('username'), request.POST.get('password')
    exist = models.AdminInfo.objects.filter(username=name).first()
    if exist:
        return render(request, 'register.html', {'error': '用户名已存在'})
    request.session['username'] = name
    models.AdminInfo.objects.create(username=name, password=password, create_time=datetime.now().strftime("%Y-%m-%d"),
                                    login_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    return redirect('/depart/list/')


def logout(request):
    request.session.clear()
    return redirect('/login/')


def chart(request):
    return render(request, 'chart.html', {"username": request.session['username']})


def chartData(request):
    departSum = models.UserInfo.objects.values("depart__title").annotate(infoSum=Count('depart_id'))
    levelSum = models.BusinessInfo.objects.values("level").annotate(infoSum=Count('id')).order_by('level')
    statusSum = models.BusinessInfo.objects.values("status").annotate(infoSum=Count('id')).order_by('status')
    monthMoney = models.BusinessInfo.objects.annotate(month=TruncMonth('create_time')).values('month').annotate(
        infoSum=Sum('price')).order_by('month')
    departInfo, levelInfo, statusInfo, monthInfo = computer(departSum), computer(levelSum), computer(
        statusSum), computer(monthMoney)
    data = {"departInfo": departInfo, "levelInfo": levelInfo, "statusInfo": statusInfo, "monthInfo": monthInfo}
    return JsonResponse(data)
